package com.lecture.java8.geekbang.demo04;


import com.lecture.javamode.oop.virtualWallet.web.VirtualWalletBo;
import com.google.protobuf.ServiceException;

import java.math.BigDecimal;

public class VirtualWalletService {

    private VirtualWalletDao walletDao;

    private VirtualWalletTransactionDao transactionDao;

    //根据钱包id获取虚拟钱包
    public VirtualWalletBo getVirtualWallet(Long walletId) {
        VirtualWalletEntity walletEntity = walletDao.getWalletEntity(walletId);
        VirtualWalletBo virtualWalletBo = convert(walletEntity);
        return virtualWalletBo;
    }

    public BigDecimal getBalance(Long walletId) {
        return walletDao.getBalance(walletId);
    }

    //出账
    public void debit(Long walletId,BigDecimal amount) throws ServiceException {
        VirtualWalletEntity walletEntity = walletDao.getWalletEntity(walletId);
        BigDecimal balance = walletEntity.getBalance();
        if (balance.compareTo(amount) < 0) {
            throw new ServiceException("余额不足");
        }
        walletDao.updateBalance(walletId,balance.subtract(amount));
    }


    //入账
    public void credit(Long walletId, BigDecimal amount) {
        VirtualWalletEntity walletEntity = walletDao.getWalletEntity(walletId);
        BigDecimal balance = walletEntity.getBalance();
        walletDao.updateBalance(walletId,balance.add(amount));
    }


    public void transfer(Long fromWalletId,Long toWalletId,BigDecimal amount) {
        VirtualWalletTransactionEntity transactionEntity = new VirtualWalletTransactionEntity();
        transactionEntity.setAmount(amount);
        transactionEntity.setCreateTime(System.currentTimeMillis());
        transactionEntity.setStatus("toBeExecuted");
        transactionEntity.setFromWalletId(fromWalletId);
        transactionEntity.setToWalletId(toWalletId);
        Long transactionId = transactionDao.saveTransaction(transactionEntity);
        try {
            debit(fromWalletId,amount);
            credit(toWalletId,amount);
        } catch (ServiceException e) {
            transactionDao.updateStatus(transactionId,"关闭");
        } catch (Exception e) {
            e.printStackTrace();
            transactionDao.updateStatus(transactionId,"失败");
        }
        transactionDao.updateStatus(transactionId,"执行");
    }




    private VirtualWalletBo convert(VirtualWalletEntity virtualWallet) {
        return new VirtualWalletBo();
    }
}
